/**
 * 版权所有(C) COVISINT 2015-2025
 * Copyright 2015-2025 COVISINT
 * 创建日期：Jul 6, 20175:05:52 PM
 * 创建人：yyang
 */
package com.wechat.framework.support;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.wechat.framework.messages.token.AccessToken;
import com.wechat.framework.utils.WechatSupportUtils;
import com.wechat.framework.utils.WechatURLUtils;

public abstract class OAuth2FrameworkSupport {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	/**
	 * 获取微信CorPid
	 * @return
	 */
	public abstract String getWechatCorPid();
	
	/**
	 * 获取微信AgentId
	 * @return
	 */
	public abstract String getWechatAgentId();
	
	/**
	 * 获取微信AccessToken
	 * @return
	 */
	public abstract AccessToken getAccessToken();
	
	/**
	 * 获取微信UserId
	 * @return
	 */
	public abstract String getWechatUserId(String accessToken,String code,String agentid);


	
	
	/**
	 * 构造参数并将请求重定向到微信API获取登录信息
	 * @param request
	 * @param resultUrl
	 * @return
	 */
	@RequestMapping("/oauth2API")
	public String Oauth2API(HttpServletRequest request, @RequestParam String resultUrl) {
		//TODO
		String redirectUrl = "";
		if (resultUrl != null) {
			//取得服务器域名
			String serverName = request.getServerName();
			String backUrl = WechatURLUtils.GET_REDIRECT_URL.replace("SERVERNAME", serverName).replace("RESULTURL", resultUrl);
			
			redirectUrl = this.oAuth2RedirectUrl(this.getWechatCorPid(), backUrl);
		}
		System.out.println("redirectUrl 3 == " + redirectUrl);
		return "redirect:" + redirectUrl;
	}
	
	
	
	/**
	 * 根据code获取Userid后跳转到需要带用户信息的最终页面
	 * @param request
	 * @param code 获取微信重定向到自己设置的URL中code参数
	 * @param oauth2url 跳转到最终页面的地址
	 * @return
	 */
	@RequestMapping("/oauth2url")
	public String Oauth2MeUrl(HttpServletRequest request, HttpServletResponse response, 
			@RequestParam String code, @RequestParam String oauth2url) {
		
		AccessToken accessToken = this.getAccessToken();
		
		HttpSession session = request.getSession();
		if (accessToken != null && accessToken.getToken() != null) {
			String userId = this.getWechatUserId(accessToken.getToken(), code, this.getWechatAgentId());
			if (userId != null) {
				//这里简单处理,存储到session中
				session.setAttribute("UserId", userId);
				System.out.println("这里存放UserId : " + userId);
				/*Cookie cookie = new Cookie("username",userId);
				cookie.setMaxAge(3600);
				response.addCookie(cookie);*/
				
				try {
					response.getWriter().print("ok");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return "redirect:" + oauth2url;
	}
	
	/**
	 * 对授权重定向的回调地址进行URLEncoder处理
	 * @param corpId
	 * @param redirectURL
	 * @return
	 */
	private String oAuth2RedirectUrl(String corpId, String redirectURL){
		try {
			redirectURL = java.net.URLEncoder.encode(redirectURL, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String oauth2Url = WechatURLUtils.GET_OAUTH2_CODE.replace("CORPID", corpId).replace("REDIRECT_URI", redirectURL);
		
		logger.info("oauth2Url = " + oauth2Url);
		return oauth2Url.toString();
	}
}
